firebase 提供簡單好用的認證註方式,如果沒server的話,這個很好用呀!!
Authentication 選擇認證的方式,這裏選擇用匿名方式,比較不會顯示個資,
大家可以依自行認證方式,來作選擇。
直接在 pubspec.yaml 加上 firebase_auth: ^4.10.1,然後pub get
dependencies:
firebase_auth: ^4.10.1
在 /lib/main.dart 加入 程式
import 'package:firebase_auth/firebase_auth.dart';
宣告和初始化
late final FirebaseApp app;
late final FirebaseAuth auth;
Future<void> firebaseAuth() async {
WidgetsFlutterBinding.ensureInitialized();
// We're using the manual installation on non-web platforms since Google sign in plugin doesn't yet support Dart initialization.
// See related issue: https://github.com/flutter/flutter/issues/96391
// We store the app and auth to make testing with a named instance easier.
app = await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
auth = FirebaseAuth.instanceFor(app: app);
if (shouldUseFirebaseEmulator) {
await auth.useAuthEmulator('localhost', 9099);
}
_showToast(auth.toString());
//runApp(const AuthExampleApp());
}
Future<void> firebaselogin() async {
try {
final UserCredential userCredential = await auth.signInAnonymously();
final User? user = userCredential.user;
//day23 fluttertoast
_showToast(user.toString());
//day9 Logger
logger.d("firebaseAuth ${user.toString()}");
print("firebaselogin "+user.toString());
} on FirebaseAuthException catch (e) {
log("firebaseAuth "+e.toString());
_showToast(e.toString());
} catch (e) {
log("firebaseAuth "+e.toString());
_showToast(e.toString());
}
}
void initState() {
firebaseAuth()
}
ElevatedButton(
onPressed: firebaselogin,
child: const Text('Day26 Firebase Auth'),
),
完整的log
firebaseAuth User(displayName: , email: , isEmailVerified: false, isAnonymous: true, metadata: UserMetadata(creationTime: 2023-10-10 06:01:37.203Z, lastSignInTime: 2023-10-10 06:01:37.203Z), phoneNumber: , photoURL: null, providerData, [], refreshToken: null, tenantId: null, uid: 0h8li89Nj6Tffk6BgmjlKBK1zpe2)
firebase 網頁
firebase_auth 用起來真的簡單方便,這裏是因為demo用匿名的方式,
還有其他的方式大家可以去用哦!!
https://firebase.google.com/docs/auth/flutter/start?hl=zh-tw